当它以'200'

时间:2017-10-25 08:17:50

标签: python

我的问题如下:
我有一个csv文件,其行通常以'200'开头。 在此文件中有不需要的换行符。

E.g。

200 Peter Pan 
200 John Smith 
200 Susan Murray 
200 Harald  
Williams
200 Liam Noah

这就是文件最后的样子:

200 Peter Pan
200 John Smith
200 Susan Murray
200 Harald Williams
200 Liam Noah

因此,每当一行不以'200'开头时,它应该附加到前一行。 我希望这对Python来说应该很容易,但到目前为止我还没有把它弄好。

4 个答案:

答案 0 :(得分:1)

with open(<file_name>, 'r+') as file:
    text = str();
    for line in file:
        if line[0:3] == "200":
            text = "{}\n{}".format(text, line.strip());
        else:
            text = "{} {}".format(text, line.strip());
    file.seek(0);
    file.write(text[1:]);

答案 1 :(得分:1)

以下代码将完成这项工作......

file名为file.csv,内容为:

200 Peter Pan 
200 John Smith 
200 Susan Murray 
200 Harald  
Williams
200 Liam Noah

我们运行以下script

之后
lines = open("file.csv", "r").read().split("\n")
for i, line in enumerate(lines):
   if not line.startswith("200"):
      lines[i-1] = lines[-1].strip() + " " + line
      lines.pop(i)

open("file.csv", "w").write("\n".join(lines)+"\n")

file已根据您的需要更新:

200 Peter Pan
200 John Smith
200 Susan Murray
200 Harald Williams
200 Liam Noah

它是如何运作的?

步骤:

  • .csv文件中以string的身份将其转换为list lines splitting string '\n'enumerated -line(lines)character。
  • 遍历list variables index and the,因此我们有两个line可以使用:"200"行。
  • 检查append是否以line开头。
  • 如果有,line indexstripping一个line之前(line之前list并添加空格之间),然后从lines popping移除index open .csv
  • 最后,我们file writing writelines相同stringlist lines。来自line的{​​{1}}的{​​{1}}是通过在每个<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit https://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <configSections> <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" /> </configSections> <appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="TemporaryUploadPath" value="" /> </appSettings> <system.web> <compilation debug="true" /> <httpRuntime maxRequestLength="2147483647"/> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> <httpModules /> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules /> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.IO.Compression.ZipFile" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /> <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> </dependentAssembly> </assemblyBinding> </runtime> <nlog xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <variable name="logPath" value="${basedir}\Logs" /> <targets async="true"> <target xsi:type="File" name="default" layout="${longdate} - ${level:uppercase=true}: ${message}${onexception:${newline}EXCEPTION\: ${exception:format=ToString}}" fileName="${logPath}\bds.api.log" keepFileOpen="false" archiveFileName="${logPath}\bds.api_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="default" /> </rules> </nlog> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:7 /nowarn:1659;1699;1701" /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:15 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" /> </compilers> </system.codedom> </configuration> 之间添加换行符来获得的,最后在末尾添加一个额外的字符。

希望这会帮助你!

答案 2 :(得分:0)

读取csv文件并遍历行:

with open('test.csv', 'r') as f:
    f_csv = csv.reader(f)
    # header = next(f_csv)
    for row in f_csv:
        if not row.startswith(200):
            #append previous row

答案 3 :(得分:0)

对我来说完全正常的代码如下:

with open('testing2.CSV', 'r+', encoding="utf-8") as file:
    text = str();
    for line in file:
        if line[0:3] == "200":
            text = text + '\n';
        text = text + line.strip();
    file.seek(0);
    file.write(text);

它甚至保留第一行,因为我的CSV文件有标题。感谢所有在这里帮助的人,特别是Benjamin James Drury和Joe Iddon。